import { fromEventPattern } from "rxjs";
import { getGraph } from '../graph-common/graph'



export function initEvents() {
    const graph = getGraph()
    //处理右键菜单事件
    // fromEventPattern(
    //     (handler) => {
    //         graph.on("cell:contextmenu", handler);
    //     },
    //     (handler) => {
    //         graph.off("cell:contextmenu", handler);
    //     }
    // ).subscribe((args) => {
       
    // });
    // //node双击事件
    // fromEventPattern(
    //     (handler) => {
    //       graph.on("cell:dblclick", handler);
    //     },
    //     (handler) => {
    //       graph.off("cell:dblclick", handler);
    //     }
    //   ).subscribe((args) => {
       
    //   });

    //处理节点连接事件
    fromEventPattern(
        (handler) => {
            graph.on("edge:connected", handler);
        },
        (handler) => {
            graph.off("edge:connected", handler);
        }
    ).subscribe((args) => {
        onConnectNode(args);
    });

    // 处理连线删除事件
    fromEventPattern(
        (handler) => {
            graph.on("edge:removed", handler);
        },
        (handler) => {
            graph.off("edge:removed", handler);
        }
        // eslint-disable-next-line consistent-return
    ).subscribe((args) => {
        onConnectionRemoved(args);
    });
    //处理节点hover
    // fromEventPattern(
    //     (handler) => {
    //         graph.on("node:mouseenter", handler);
    //     },
    //     (handler) => {
    //         graph.off("node:mouseenter", handler);
    //     }
    // ).subscribe((args) => {
    //    console.log(args)
    //     const { node } = args;
    //   //  node.setPortProp('opacity',1)
    //   //  node.ports.groups.in.attrs.circle.opacity=1
    //     //node.ports.groups.out.attrs.circle.opacity=1
    //     // setCellsSelectedStatus(removed, false);
    //     // setCellsSelectedStatus(selected, true);
    //     //selectedNodes$.next(selected)
    // });
    // 处理窗口缩放
    fromEventPattern(
        (handler) => {
            window.addEventListener('resize', handler)
        },
        (handler) => {
            window.removeEventListener('resize', handler)
        },
    ).subscribe(resizeGraph)

    // 处理删除节点或连线事件
    fromEventPattern(
        (handler) => {
            graph.bindKey(['delete', 'backspace'], handler)
        },
        () => {
            graph.unbindKey(['delete', 'backspace'])
        },
    ).subscribe(() => {
        const selectedCells = graph.getSelectedCells()
        const selectedNodes = selectedCells.filter((cell) =>
            cell.isNode(),
        )
        const selectedEdges = selectedCells.filter((cell) =>
            cell.isEdge(),
        )
        onDeleteNodeOrEdge({ nodes: selectedNodes, edges: selectedEdges })
    })

    // 按下删除键的回调，默认参数为当前选中的节点和边
    function onDeleteNodeOrEdge(args) {
        if (process.env.NODE_ENV === 'development') {
            console.log('[GraphCore] delete node or edge:', args)
        }
    }

    // function setCellsSelectedStatus(cells, selected) {
    //     cells.forEach((cell) => {
    //         const data = cell.getData() || {};
    //         cell.setData({ ...data, selected });
    //     });
    // }
    async function onConnectNode(args) {
        const { edge = {}, isNew } = args;
        const { source, target } = edge;
        if (isNew) {
            // 处理边虚线样式更新的问题。
            const node = args.currentCell;
            const portId = edge.getTargetPortId();
            if (node && portId) {
                // 触发 port 重新渲染
                node.setPortProp(portId, "connected", true);
                // 更新连线样式
                edge.attr({
                    line: {
                        strokeDasharray: "",
                        targetMarker: "classic",
                        stroke: "#808080",
                    },
                });
                const data = {
                    source: source.cell,
                    target: target.cell,
                    outputPortId: source.port,
                    inputPortId: target.port,
                };
                edge.setData(data);
            }
        }

        return { success: true };
    }

    // eslint-disable-next-line class-methods-use-this
    const onConnectionRemoved = (args) => {
        try {
      
            const { edge } = args;
            const { target } = edge;
            const { cell: nodeId, port: portId } = target;

            if (nodeId) {
                const targetCell = getNodeById(nodeId);
                if (targetCell) {
                    // 触发 port 重新渲染
                    targetCell.setPortProp(portId, "connected", false);
                }
            }
        } catch (error) {
            console.warn(error);
        }
    }
    const getNodeById = (nodeId) => {
        const node = graph.getCellById(nodeId)
        if (node?.isNode()) {
            return node
        }
        return undefined
    }
    function resizeGraph() {
        // console.log(graph)
        // const { graph, wrapper } = this
        // if (graph && wrapper) {
        //   requestAnimationFrame(() => {
        //     const width = wrapper.clientWidth
        //     const height = wrapper.clientHeight
        //     graph.resize(width, height)
        //   })
        // }
    }
}
// 处理产生连线事件
